<template>
  <el-dialog class="assign-role" title="分配角色" :visible="showRoleDialog" :close-on-click-modal="false" @open="openDailog" @close="closeDailog">
    <!-- 这里准备复选框 -->
    <el-checkbox-group v-model="roleIds" v-loading="isLoading">
      <el-checkbox v-for="e in list" :key="e.id" :label="e.id">{{ e.name }}</el-checkbox>

    </el-checkbox-group>

    <template #footer>
      <el-button type="primary" size="small" @click="assignUser">确定</el-button>
      <el-button size="small" @click="closeDailog">取消</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { getRoleListApi } from '@/api/setting'
import { getUserPhoto, assignUserApi } from '@/api/user'
import { Message } from 'element-ui'
export default {
  props: {
    showRoleDialog: {
      type: Boolean,
      default: false
    },
    // 用户的id 用来查询当前用户的角色信息
    userId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      list: [],
      roleIds: [],
      isLoading: false
    }
  },
  methods: {
    /**
     * 关闭和取消
     */
    closeDailog() {
      this.$emit('update:showRoleDialog', false)
    },
    /**
     * 打开弹窗
     */
    async openDailog() {
    // 开启加载
      this.isLoading = true
      // 由于接口请求时异步操作 所以要等待一下
      await this.getRoleList()
      await this.getUserQX()
      // 关闭加载
      this.isLoading = false
    },
    /**
     * 获取权限列表
     */
    async getRoleList() {
      const { data: { rows }} = await getRoleListApi(1, 99999)
      this.list = rows
      console.log(this.list)
    },
    /**
     * 获取用户权限信息进行回显
     */
    async getUserQX() {
      const { data: { roleIds }} = await getUserPhoto(this.userId)
      this.roleIds = roleIds || []
    },
    /**
     * 确定更新按钮
     */
    async assignUser() {
      // 1.请求接口
      await assignUserApi(this.userId, this.roleIds)
      // 2.提示成功
      Message.success('修改成功')
      // 3.关闭弹窗
      this.closeDailog()
    }
  }
}
</script>
